package cn.wjx.taobaounion.ui.fragment;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TbNestedScrollView;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import java.util.List;

import butterknife.BindView;
import cn.wjx.taobaounion.R;
import cn.wjx.taobaounion.base.BaseFragment;
import cn.wjx.taobaounion.model.domain.Categories;
import cn.wjx.taobaounion.model.domain.CategoryContent;
import cn.wjx.taobaounion.model.domain.IBaseGoodsItemInfo;
import cn.wjx.taobaounion.presenter.ICategoryPagerPresenter;
import cn.wjx.taobaounion.presenter.ITicketPresenter;
import cn.wjx.taobaounion.ui.activity.TicketActivity;
import cn.wjx.taobaounion.ui.adapter.HomeContentListAdapter;
import cn.wjx.taobaounion.ui.adapter.LooperPagerAdapter;
import cn.wjx.taobaounion.ui.custom.AutoLooperViewpager;
import cn.wjx.taobaounion.utils.Constants;
import cn.wjx.taobaounion.utils.LogUtils;
import cn.wjx.taobaounion.utils.PresenterManger;
import cn.wjx.taobaounion.utils.SizeUtils;
import cn.wjx.taobaounion.utils.ToastUtil;
import cn.wjx.taobaounion.view.ICategoryPagerCallback;

/**
 * @author WuChangJian
 * @date 2020/6/17 13:30
 */
public class HomePagerFragment extends BaseFragment implements ICategoryPagerCallback, HomeContentListAdapter.OnItemClickListener, LooperPagerAdapter.OnLooperPagerClickListener {

    private ICategoryPagerPresenter mCategoryPagerPresenter;
    private int mMaterialId;
    private HomeContentListAdapter mHomeContentListAdapter;
    private LooperPagerAdapter mLooperPagerAdapter;

    @BindView(R.id.home_pager_content_list)
    public RecyclerView mContentList;

    @BindView(R.id.looper_pager)
    public AutoLooperViewpager mLooperPager;

    @BindView(R.id.home_pager_title)
    public TextView mPagerTitle;

    @BindView(R.id.looper_pager_indicator)
    public LinearLayout mLooperIndicator;

    @BindView(R.id.home_pager_refresh)
    public TwinklingRefreshLayout mPagerRefresh;

    @BindView(R.id.home_pager_parent)
    public LinearLayout mHomePagerContainer;

    @BindView(R.id.home_looper_title_container)
    public LinearLayout mLooperTitleContainer;

    @BindView(R.id.home_pager_nested_scroll)
    public TbNestedScrollView mHomePagerScrollView;

    public static HomePagerFragment newInstance(Categories.DataBean category) {
        HomePagerFragment homePagerFragment = new HomePagerFragment();
        Bundle bundle = new Bundle();
        bundle.putString(Constants.KEY_HOME_PAGER_TITLE, category.getTitle());
        bundle.putInt(Constants.KEY_HOME_PAGER_MATERIAL_ID, category.getId());
        homePagerFragment.setArguments(bundle);
        return homePagerFragment;
    }

    @Override
    protected int getRootViewResId() {
        return R.layout.fragment_home_pager;
    }

    @Override
    protected void initView(View rootView) {
        // recyclerView
        mHomeContentListAdapter = new HomeContentListAdapter();
        mContentList.setLayoutManager(new LinearLayoutManager(getContext()));
        mContentList.setAdapter(mHomeContentListAdapter);
        mContentList.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.top = 8;
                outRect.bottom = 8;//px
            }
        });
        // 轮播图
        mLooperPagerAdapter = new LooperPagerAdapter();
        mLooperPager.setAdapter(mLooperPagerAdapter);
        // 数据加载
        // 禁止任何刷新
        mPagerRefresh.setEnableRefresh(false);
        // 设置上拉加载
        mPagerRefresh.setEnableLoadmore(true);
    }

    @Override
    protected void initListener() {
        // 拿到父容器,设置全局监听，当页面布局改变(滑动时)改变RecyclerView高度为父容器高度
        mHomePagerContainer.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                // 解决绘制和执行不同步带来的空指针异常问题
                if (mHomePagerContainer == null) {
                    return;
                }
                int measuredHeight = mHomePagerContainer.getMeasuredHeight();
                int headDistance = mLooperTitleContainer.getMeasuredHeight();
                //LogUtils.d(this, "measure height -->" + measuredHeight);
                //LogUtils.d(this, "header distance -->" + headDistance);
                ViewGroup.LayoutParams layoutParams = mContentList.getLayoutParams();
                layoutParams.height = measuredHeight;
                // 设置recyclerview的高度
                mContentList.setLayoutParams(layoutParams);
                // 设置TBNestedScrollView高度
                mHomePagerScrollView.setHeaderDistance(headDistance);

                if (measuredHeight != 0) {
                    mHomePagerContainer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
            }
        });

        // 为轮播图viewpager设置滑动监听，动态改变indicator颜色
        mLooperPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //LogUtils.d(HomePagerFragment.this, "LooperPager设置监听 data size --> " + mLooperPagerAdapter.getDataSize());
                if (mLooperPagerAdapter.getDataSize() == 0)
                    return;
                int targetPosition = position % mLooperPagerAdapter.getDataSize();
                updateIndicatorColor(targetPosition);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mPagerRefresh.setOnRefreshListener(new RefreshListenerAdapter() {

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                LogUtils.d(HomePagerFragment.this, "加载更多...");
                new Handler().postDelayed(() -> {
                    // 拿到数据-> cancel loading 完成加载更多
                    mCategoryPagerPresenter.loaderMore(mMaterialId);
                }, 3000);
            }
        });
        // recycler view item的点击监听
        mHomeContentListAdapter.setOnItemClickListener(this);
        // looper pager的点击监听
        mLooperPagerAdapter.setOnLooperPagerClickListener(this);
    }

    private void updateIndicatorColor(int targetPosition) {
        for (int i = 0; i < mLooperIndicator.getChildCount(); i++) {
            View point = mLooperIndicator.getChildAt(i);
            if (i == targetPosition) {
                point.setBackgroundResource(R.drawable.shape_looper_indicator_selected_bg);
            } else {
                point.setBackgroundResource(R.drawable.shape_looper_indicator_bg);
            }
        }
    }

    @Override
    protected void initPresenter() {
        // 设置为单例
        mCategoryPagerPresenter = PresenterManger.getInstance().getCategoryPagerPresenter();
        mCategoryPagerPresenter.registerViewCallback(this);
    }

    @Override
    protected void loadData() {
        Bundle bundle = getArguments();
        String title = bundle.getString(Constants.KEY_HOME_PAGER_TITLE);
        // mMaterialId设置为成员变量，为后面多个Tab下是否为当前tab做判断
        mMaterialId = bundle.getInt(Constants.KEY_HOME_PAGER_MATERIAL_ID);
        LogUtils.d(this, "title-->" + title);
        LogUtils.d(this, "materialId-->" + mMaterialId);
        if (mCategoryPagerPresenter != null) {
            mCategoryPagerPresenter.getContentByCategoryId(mMaterialId);
        }
        if (mPagerTitle != null) {
            mPagerTitle.setText(title);
        }

    }

    @Override
    public int getCategoryId() {
        return mMaterialId;
    }

    @Override
    protected void release() {
        mCategoryPagerPresenter.unregisterViewCallback(this);
    }

    @Override
    public void onContentLoaded(List<CategoryContent.DataBean> contents) {
        setUpState(State.SUCCESS);
        mHomeContentListAdapter.setData(contents);
    }

    @Override
    public void onLooperListLoaded(List<CategoryContent.DataBean> contents) {
        LogUtils.d(this, "looper data --> " + contents);
        // 伪轮播 将页面设置到中间点 但是如果直接setCurrentItem(Integer.MAX_VALUE / 2);
        // 并不能保证Integer.MAX_VALUE/2模运算size之后为0
        int dv = Integer.MAX_VALUE / 2 % contents.size();
        // 解决：取模、差值 就能保证显示第一个数据
        int targetPosition = Integer.MAX_VALUE / 2 % contents.size() - dv;
        mLooperPager.setCurrentItem(targetPosition);
        // LogUtils.d(this, "pic url -- > " + contents.get(0).getPict_url());
        mLooperIndicator.removeAllViews();
        for (int i = 0; i < contents.size(); i++) {
            int size = SizeUtils.dip2px(getContext(), 8);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(size, size);
            layoutParams.setMarginStart(SizeUtils.dip2px(getContext(), 5));
            layoutParams.setMarginEnd(SizeUtils.dip2px(getContext(), 5));
            View point = new View(getContext());
            point.setLayoutParams(layoutParams);
            if (i == 0) {
                point.setBackgroundResource(R.drawable.shape_looper_indicator_selected_bg);
            } else {
                point.setBackgroundResource(R.drawable.shape_looper_indicator_bg);
            }
            mLooperIndicator.addView(point);
        }

        mLooperPagerAdapter.setData(contents);

    }

    @Override
    public void onResume() {
        super.onResume();
        mLooperPager.startLooper();
    }

    @Override
    public void onPause() {
        super.onPause();
        mLooperPager.stopLooper();
    }

    @Override
    public void onLoading() {
        setUpState(State.LOADING);
    }

    @Override
    public void onEmpty() {
        setUpState(State.EMPTY);
    }

    @Override
    public void onError() {
        setUpState(State.ERROR);
    }

    @Override
    public void onLoaderMoreError() {
        ToastUtil.showToast("加载数据失败,请稍候重试");
        if (mPagerRefresh != null) {
            mPagerRefresh.finishLoadmore();
        }
    }

    @Override
    public void onLoaderMoreEmpty() {
        ToastUtil.showToast("加载数据为空");
        if (mPagerRefresh != null) {
            mPagerRefresh.finishLoadmore();
        }
    }

    @Override
    public void onLoaderMoreLoaded(List<CategoryContent.DataBean> contents) {
        if (mHomeContentListAdapter != null) {
            mHomeContentListAdapter.addData(contents);
        }
        if (mPagerRefresh != null) {
            mPagerRefresh.finishLoadmore();
            ToastUtil.showToast("加载了"+contents.size()+"条数据");
        }
    }

    @Override
    public void OnItemClick(IBaseGoodsItemInfo item) {
        launchActivity(item);
    }

    private void launchActivity(IBaseGoodsItemInfo item) {
        String title = item.getTitle();
        // 领券的Url 若没有优惠券，则跳转到商品详情 重写接口的方法做了处理
        String url = item.getUrl();
        String cover = item.getCover();
        ITicketPresenter ticketPresenter = PresenterManger.getInstance().getTicketPresenter();
        ticketPresenter.getTicket(title, cover, url);
        Intent intent = new Intent(getContext(), TicketActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("url", url);
        intent.putExtra("cover", cover);
        startActivity(intent);
        //TicketUtil.toTicketPage(getContext(), item); 重构（保留）
    }

    @Override
    public void onLooperPagerClick(CategoryContent.DataBean item) {
        launchActivity(item);
    }
}
